package com.ship.common.core.utils;

import com.ship.common.core.exception.ServiceException;
import com.ship.common.core.web.domain.BaseResultCode;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <b>FileUtils</b>
 *
 * @description: FileUtils <br>
 * @date: 2024/9/24 16:26 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */
public class FileUtils {

    public static boolean checkFileName(MultipartFile file){
        List<String> typeList = new ArrayList<>();
        typeList.add("image/jpeg");
        typeList.add("image/png");
//        typeList.add("image/gif");
//        typeList.add("image/bmp");
        typeList.add("application/pdf");
        typeList.add("application/word");
        typeList.add("application/excel");
        typeList.add("application/zip");
        typeList.add("application/octet-stream");
        typeList.add("multipart/form-data");
        typeList.add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        typeList.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

        String contentType = file.getContentType();
//        System.out.println("contentType: "+contentType);
        if (!typeList.contains(contentType)){
            throw new ServiceException("禁止上传类型文件！", BaseResultCode.GENERAL_ERROR.getCode());
        }
        String fileName = file.getOriginalFilename();
//        System.out.println("fileName: "+fileName);
        List<String> list = new ArrayList<>();
        list.add("jpg");
        list.add("png");
        list.add("pdf");
        list.add("xlsx");
        list.add("csv");
        list.add("doc");
        list.add("docx");
        list.add("xls");
        list.add("zip");
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); // 获取后缀并转为小写
            if (!list.contains(suffixName)){
                throw new ServiceException("禁止上传类型文件！", BaseResultCode.GENERAL_ERROR.getCode());
            }
            return true;
        } else {
            return true;
        }
    }
}
